package function;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Set;
import java.util.zip.InflaterInputStream;

import javax.print.DocFlavor.URL;

import frame.master;
import frame.data.contrldata;
import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;

public class filelibrary {
	private HashMap<Integer, fileinfo> filelist=new HashMap<>();
	private HashMap<Integer, Boolean> fileisupdate=new HashMap<>();
	private HashMap<Integer, String> oldurl=new HashMap<>();
	private DataEnAndDe ed=new DataEnAndDe();
	public filelibrary() {
		if(loadcachefile()) {
			if(filelist.size()<1) {
				createfile();
			}
		}else {
			System.exit(3);
		}
	}
	/**
	 * 设置文件是否被修改
	 * @param num
	 */
	public void setfileisupdateofnum(int num) {
		fileisupdate.put(num, true);
	}
	/**
	 * 创建文件
	 * @return
	 */
	public boolean createfile() {
		try {
			int a=filelist.size();
			filelist.put(a,new fileinfo("new_file_"+filelist.size(),"./data/cache","UTF-8",0,"txt",new HashMap<Integer,String>()));
			fileisupdate.put(a, false);
			master.editfilenum=a;
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	/**
	 * 打开文件
	 * @param url
	 * @return bool
	 */
	public boolean openfile(String url) {
		try {
			File f=new File(url);
			String code=getfilecode(f);
			BufferedReader re=new BufferedReader(new FileReader(f));
			HashMap<Integer,String> content=new HashMap<>();
			int i=0;
			String a;
			while((a=re.readLine())!=null)content.put(i++,a);
			re.close();
			addfiletolist(url,code,content);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 打开vw文件
	 */
	public boolean openvwfile(String url) {
		try {
			BufferedReader re=new BufferedReader(new InputStreamReader(new InflaterInputStream(new FileInputStream(url)),"UTF-8"));
			String a=null;
			int i=0;
			HashMap<Integer,String> content=new HashMap<>();
			while((a=ed.dataDecrypt(re.readLine()))!=null)content.put(i++,a);
			re.close();
			addfiletolist(url,"UTF-8",content);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	private void addfiletolist(String url,String code,HashMap<Integer,String> content) {
		File f=new File(url);
		String ty=f.getName().substring(f.getName().lastIndexOf(".")+1);
		master.editfilenum=filelist.size();
		int num=filelist.size();
		filelist.put(num,new fileinfo(f.getName(),f.getPath(),code,f.length(),ty,content));
		oldurl.put(num,url);
	}
	/**
	 * 获取文件编码
	 * @param file
	 * @return
	 */
	private String getfilecode(File f) {
		try {
			CodepageDetectorProxy co=CodepageDetectorProxy.getInstance();//创建探测器
			/*
			 * ParsingDetector可用于检查HTML、XML等文件或字符流的编码,构造方法中的参数用于
			 * 指示是否显示探测过程的详细信息，为false不显示。
			 */
			co.add(new ParsingDetector(false));
			co.add(JChardetFacade.getInstance());// 用到antlr.jar、chardet.jar
			co.add(ASCIIDetector.getInstance());// ASCIIDetector用于ASCII编码测定
			co.add(UnicodeDetector.getInstance());// UnicodeDetector用于Unicode家族编码的测定
			java.nio.charset.Charset cha=null;
			cha =co.detectCodepage(f.toURI().toURL());//开始检测
			if(cha!=null)return cha.name();
			else return "UTF-8";
		}catch (Exception e) {
			return "UTF-8";
		}
	}
	/**
	 * 加载缓存文件
	 * @return
	 */
	public boolean loadcachefile() {
		try {
			BufferedReader re=new BufferedReader(new FileReader(new File("./data/cachelist")));
			String a;
			int i=0;
			while((a=re.readLine())!=null) {
				a=a.substring(5, a.length()-1);
				String[] s=a.split(",");
				if(openfile("./data/cache/"+s[0].split(":")[1]))
					oldurl.put(i, s[1].split(":")[1]);
				i++;
			}
			re.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	/**
	 * 删除文件（关闭）,根据编号
	 * @param num
	 * @param ma
	 */
	public void deletefileofnum(int num,master ma) {
		filelist.remove(num);
		fileisupdate.remove(num);
		oldurl.remove(num);
		if(num==master.editfilenum)master.editfilenum=master.fl.getfilenum()-1;
		if(filelist.size()==0)createfile();
		contrldata.filetab.updateUI();
		master.t1l.addtexttoarea(ma);
	}
	public String getfileoldurlofnum(int num) {
		if(oldurl.containsKey(num))return oldurl.get(num);
		else return null;
	}
	public boolean isfileupdateofnum(int num) {
		return fileisupdate.get(num);
	}
	public int getfilenum() {
		return filelist.size();
	}
	public String getfilenameofnum(int num) {
		return  filelist.get(num).getName();
	}
	public fileinfo getfileinfoofnum(int num) {
		return filelist.get(num);
	}
}
